package lesson.base.paramresolve;



import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateKit {

    public static final String DATE_YMDHMS = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_YMDHM = "yyyy-MM-dd HH:mm";
    public static final String DATE_YMD = "yyyy-MM-dd";
    public static final String DATE_MDHM = "MM-dd HH:mm";
    public static final String DATE_MDHMS = "MM-dd HH:mm:ss";
    public static final String DATE_HMS = "HH:mm:ss";
    public static final String DATE_MD = "MM-dd";
    public static final String DATE_HM = "HH:mm";


    /**
     * 字符串转Date，支持以下格式的转换：<br/>
     * 时间戳 <br/>
     * yyyy-MM-dd HH:mm:ss<br/>
     * yyyy-MM-dd<br/>
     * MM-dd<br/>
     * HH:mm:ss<br/>
     * HH:mm<br/>
     *
     * @param date
     * @return
     */
    public static Date parseDate(String date) {
        if (StringKit.isBlank(date)) {
            return null;
        }
        date = date.replace("T", " ");
        switch (date.length()) {
            case 19: //2020-09-09 11:00:00
                return DateKit.parse(date, DATE_YMDHMS);
            case 16: //2020-09-09 11:00
                return DateKit.parse(date, DATE_YMDHM);
            case 14: //09-09 10:10:10
                return DateKit.parse(date, DATE_MDHMS);
            case 13: //时间戳
                return new Date(Long.valueOf(date));
            case 11: //09-09 10:10
                return DateKit.parse(date, DATE_MDHM);
            case 10: //2020-09-09
                return DateKit.parse(date, DATE_YMD);
            case 8: //00:00:00
                return DateKit.parse(date, DATE_HMS);
            case 5: //01-01或者 00：00
                if (date.indexOf("-")>0) {
                    return DateKit.parse(date, DATE_MD);
                } else if (date.indexOf(":") > 0) {
                    return DateKit.parse(date, DATE_HM);
                }

            default:
                throw new RuntimeException("无法识别"+date+"，无法转换为Date类型");
        }
    }

    public static Date parse(String date, String fmt) {
        SimpleDateFormat format = new SimpleDateFormat(fmt);
        try {
            return format.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
    public static String format(Date date, String fmt) {
        SimpleDateFormat format = new SimpleDateFormat(fmt);
        try {
            return format.format(date);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }




}
